package ypt.fqh.maptest1;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import android.Manifest;
import android.location.Location;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.SearchView;
import android.widget.Toast;

import com.tencent.lbssearch.TencentSearch;
import com.tencent.lbssearch.httpresponse.HttpResponseListener;
import com.tencent.lbssearch.object.param.SearchParam;
import com.tencent.lbssearch.object.result.SearchResultObject;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory;
import com.tencent.tencentmap.mapsdk.maps.LocationSource;
import com.tencent.tencentmap.mapsdk.maps.MapView;
import com.tencent.tencentmap.mapsdk.maps.TencentMap;
import com.tencent.tencentmap.mapsdk.maps.TencentMapInitializer;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptorFactory;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;
import com.tencent.tencentmap.mapsdk.maps.model.Marker;
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions;
import com.tencent.tencentmap.mapsdk.maps.model.MyLocationStyle;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;
import ypt.fqh.maptest1.adapter.SearchResultsAdapter;

/**
 *
 * 搜索选点
 */
public class MainActivity3 extends AppCompatActivity implements EasyPermissions.PermissionCallbacks,
        LocationSource, TencentLocationListener {

    private SearchView searchView;

    private MapView mapView;

    private TencentMap tencentMap;

    private Marker marker;

    private TencentSearch mTencentSearch;

    private RecyclerView recyclerView;

    private OnLocationChangedListener locationChangedListener;

    private TencentLocationManager locationManager;

    private TencentLocationRequest locationRequest;

    private SearchResultsAdapter searchResultsAdapter;

    List<SearchResultObject.SearchResultData> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        TencentMapInitializer.setAgreePrivacy(true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        requestDynamicPermisson();

        searchView = findViewById(R.id.searchView);

        mapView = findViewById(R.id.mapview);

        tencentMap = mapView.getMap();

        recyclerView = findViewById(R.id.recyclerV);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        mTencentSearch = new TencentSearch(this);

        //用于访问腾讯定位服务的类, 周期性向客户端提供位置更新
        locationManager = TencentLocationManager.getInstance(this);
        //设置坐标系
        locationManager.setCoordinateType(TencentLocationManager.COORDINATE_TYPE_GCJ02);
        //创建定位请求
        locationRequest = TencentLocationRequest.create();
        //设置定位周期（位置监听器回调周期）为3s
        locationRequest.setInterval(10000);
        //地图上设置定位数据源
        tencentMap.setLocationSource(this);
        //设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        tencentMap.setMyLocationEnabled(true);
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        //默认连续定位，且将视角移动到地图中心，并且会跟随设备移动,默认是此种类型
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);
        tencentMap.setMyLocationStyle(myLocationStyle);

        addMarker(new LatLng(0,0));

        initListener();
    }


    private void initListener() {
        // 设置SearchView的文本变化监听器
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // 当用户提交搜索时调用此方法
                // 在这里可以处理搜索提交的逻辑
                System.out.println("提交搜索:queryStr="+query);
                TencentLocation lastKnownLocation = locationManager.getLastKnownLocation();
                SearchParam param = new SearchParam();
                param.keyword(query).boundary(new SearchParam.Region(lastKnownLocation.getCity()));
                System.out.println("请求参数param="+param);
                recyclerView.setVisibility(View.VISIBLE);
                mTencentSearch.search(param, new HttpResponseListener<SearchResultObject>() {
                    @Override
                    public void onSuccess(int pI, SearchResultObject pSearchResultObject) {
                        if (pSearchResultObject != null) {
                            System.out.println("请求成功,data="+pSearchResultObject.data);
                            recyclerView.setVisibility(View.VISIBLE);
                            searchResultsAdapter = new SearchResultsAdapter(pSearchResultObject.data);
                            recyclerView.setAdapter(searchResultsAdapter);
                        }
                    }

                    @Override
                    public void onFailure(int pI, String pS, Throwable pThrowable) {
                        Log.e("请求失败", pS, pThrowable);
                    }
                });
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                // 当搜索框文本发生变化时调用此方法
                // 在这里可以处理搜索框文本变化的逻辑
                // newText 参数即为当前搜索框中的文本
                return true;
            }
        });
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {}

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {}

    @Override
    protected void onStart() {
        super.onStart();
        mapView.onStart();
    }

    // 在生命周期方法中调用 MapView 对应的方法
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mapView.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {
        if(i == TencentLocation.ERROR_OK && locationChangedListener != null){
            Location location = new Location(tencentLocation.getProvider());
            //设置经纬度
            location.setLatitude(tencentLocation.getLatitude());
            location.setLongitude(tencentLocation.getLongitude());
            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
            marker.setPosition(latLng);
            tencentMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
        }
    }

    @Override
    public void onStatusUpdate(String s, int i, String s1) {

    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        locationChangedListener = onLocationChangedListener;
        //开启定位
        int err = locationManager.requestLocationUpdates(
                locationRequest, this, Looper.myLooper());
        switch (err) {
            case 1:
                Toast.makeText(this,
                        "设备缺少使用腾讯定位服务需要的基本条件",
                        Toast.LENGTH_SHORT).show();
                break;
            case 2:
                Toast.makeText(this,
                        "manifest 中配置的 key 不正确", Toast.LENGTH_SHORT).show();
                break;
            case 3:
                Toast.makeText(this,
                        "自动加载libtencentloc.so失败", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

    @Override
    public void deactivate() {

    }

    private void addMarker(LatLng position) {
        if (marker != null) return;
        MarkerOptions options = new MarkerOptions();
        options.icon(BitmapDescriptorFactory.fromResource(R.mipmap.taxi));
        options.anchor(0.5f, 0.5f);
        options.position(position);
        marker = tencentMap.addMarker(options);
        System.out.println("marker1:::"+marker);
    }


    private void requestDynamicPermisson() {
        //定位需要申请的权限
        String[] perms = {
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.READ_PHONE_STATE
        };

        if (EasyPermissions.hasPermissions(this, perms)) {
            Log.i("location", "已获取权限");
        } else {
            EasyPermissions.requestPermissions(this, "必要的权限", 0, perms);
        }
    }

}